
package de.justphil.tcg.tcgandroidclient.network.websocket;

import org.json.JSONException;
import org.json.JSONObject;

import de.justphil.tcg.tcgandroidclient.msgdata.Join;
import de.justphil.tcg.tcgandroidclient.util.TCGLog;
import android.os.Message;

public class WebSocketMessageEncoder {
	
	public static String encodeMessage(Message msg) {
	
		JSONObject msgJson = new JSONObject();
		try {
			switch (msg.what) {
				case WebSocketService.MSG_RESUME:
					/* MSG_RESUME */
					msgJson.put("subject", "game-p");
					JSONObject resumeJson = new JSONObject();
					resumeJson.put("cmd", "resume");
					msgJson.put("p", resumeJson);
					break;
				case WebSocketService.MSG_SELECT:
					/* MSG_SELECT */
					msgJson.put("subject", "game-p");
					JSONObject selectJson = new JSONObject();
					selectJson.put("cmd", "select");
					selectJson.put("s", msg.arg1);
					msgJson.put("p", selectJson);
					break;
				case WebSocketService.MSG_JOIN:
					/* MSG_SELECT */
					Join join = (Join) msg.obj;
					msgJson.put("subject", "game-j");
					msgJson.put("l", join.getLanguage());
					JSONObject joinJson = new JSONObject();
					joinJson.put("gameId", join.getGameId());
					joinJson.put("playerId", join.getPlayerId());
					joinJson.put("otp", join.getOtp());
					msgJson.put("j", joinJson);
					break;
				case WebSocketService.MSG_QUIT:
					/* MSG_SELECT */
					msgJson.put("subject", "game-q");
					break;
			}
		}
		catch (JSONException e) {
			TCGLog.e(new Object[] {
				"Error creating JsonObject: " }, e);
		}
		String msgString = msgJson.toString();
		TCGLog.d(new Object[] {
				"Sending message: ", msgString });
		return msgString;
	}
}
